package harima.agamengine.loaders;

import harima.agamengine.mapmodel.MapModel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import Tests.MapModel.MapModelFixture;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class XmlMapModelSerializer implements IMapSerializer{

	final String FileExtension  = ".xmap.xml";
	public File createFile(String fileName) throws IOException {
		File file = new File(fileName + FileExtension);
		file.createNewFile();
		return file;
	}

	public MapModel readFromFile(String fileName) throws IOException, ClassNotFoundException {
		XStream xstream = createCrossPlatformXStream();
		FileReader reader = new FileReader(new File(fileName + FileExtension));
		Object data = xstream.fromXML(reader);
		reader.close();
		return (MapModel)data;
	}

	public void writeToFile(String file, MapModel model) throws FileNotFoundException, IOException {
		XStream xtream = createCrossPlatformXStream();
		FileWriter fileWrite = new FileWriter(file + FileExtension);
		xtream.toXML(model, fileWrite);
		fileWrite.close();
	}

	public String getFileExtension() {
		return FileExtension;
	}

	
	private XStream createCrossPlatformXStream()
	{
		XStream xstream = new XStream( 
			     new XppDriver() { 
			         public HierarchicalStreamWriter createWriter(Writer out) { 
			             return new PrettyPrintWriter(out, "  ", System.getProperty("line.separator"));
			         } 
			     } 
			 ); 
		return xstream;
	}

	public File[] findMapsInDir(File direcory) {
		
		File[] files = direcory.listFiles(new FileFilter(){
			public boolean accept(File suspect)
			{
				return suspect.getName().endsWith(FileExtension);
			}
		});
		
		return files;
	}
}
